﻿using System;
using Bitmap = System.Drawing.Bitmap;
using CopyPixelOperation = System.Drawing.CopyPixelOperation;

namespace AdTech.Snap.Interop
{
    /// <summary>
    /// Win32 API Helper to create bitmaps from screen.
    /// </summary>
    internal static class CaptureScreenHelper
    {
        /// <summary>
        /// Creates a bitmap from screen.
        /// </summary>
        /// <param name="destination">The target file path.</param>
        /// <param name="x">The x-axis position of the top left point of the desired rectangle to crop.</param>
        /// <param name="y">The y-axis position of the top left point.</param>
        /// <param name="width">The width of the desired rectangle to crop.</param>
        /// <param name="height">The height of the desired rectangle to crop.</param>
        public static void CopyFromScreen(string destination, int x, int y, int width, int height)
        {
            IntPtr hDesk = NativeMethods.GetDesktopWindow();
            IntPtr hdcSrc = NativeMethods.GetWindowDC(hDesk);
            IntPtr hdcDest = NativeMethods.CreateCompatibleDC(hdcSrc);
            IntPtr hBmp = NativeMethods.CreateCompatibleBitmap(hdcSrc, width, height);
            IntPtr hOldBmp = NativeMethods.SelectObject(hdcDest, hBmp);
            bool b = NativeMethods.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt);
            using (Bitmap bmp = Bitmap.FromHbitmap(hBmp))
            {
                NativeMethods.SelectObject(hdcDest, hOldBmp);
                NativeMethods.DeleteObject(hBmp);
                NativeMethods.DeleteDC(hdcDest);
                NativeMethods.ReleaseDC(hDesk, hdcSrc);
                bmp.Save(destination);
            }
        }

    }
}
